import 'dart:convert';

import 'package:http/http.dart' as http;

import '../models/order.dart';
import 'auth_service.dart';

class OrderService {
  static const String _baseUrl = 'http://127.0.0.1:3000/api';
  final AuthService _authService;

  OrderService(this._authService);

  Future<List<Order>> getOrders({
    int page = 1,
    int limit = 20,
    String? status,
  }) async {
    try {
      final queryParams = {
        'page': page.toString(),
        'limit': limit.toString(),
        if (status != null) 'status': status,
      };

      final uri = Uri.parse('$_baseUrl/orders').replace(queryParameters: queryParams);
      final response = await http.get(
        uri,
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        return (data['orders'] as List).map((json) => Order.fromJson(json)).toList();
      }
      return [];
    } catch (e) {
      print('获取订单列表失败: $e');
      return [];
    }
  }

  Future<Order?> getOrderById(String id) async {
    try {
      final response = await http.get(
        Uri.parse('$_baseUrl/orders/$id'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      if (response.statusCode == 200) {
        return Order.fromJson(jsonDecode(response.body));
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  Future<Order?> createOrder({
    required String shippingAddress,
    required String paymentMethod,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$_baseUrl/orders'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
        body: jsonEncode({
          'shippingAddress': shippingAddress,
          'paymentMethod': paymentMethod,
        }),
      );

      if (response.statusCode == 201) {
        return Order.fromJson(jsonDecode(response.body));
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  Future<bool> cancelOrder(String orderId) async {
    try {
      final response = await http.post(
        Uri.parse('$_baseUrl/orders/$orderId/cancel'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
      );

      return response.statusCode == 200;
    } catch (e) {
      return false;
    }
  }

  // Admin only
  Future<bool> updateOrderStatus({required String orderId, required OrderStatus status}) async {
    try {
      final response = await http.put(
        Uri.parse('$_baseUrl/orders/$orderId/status'),
        headers: {
          'Content-Type': 'application/json',
          if (_authService.token != null) 'Authorization': 'Bearer ${_authService.token}',
        },
        body: jsonEncode({'status': status.toString().split('.').last}),
      );

      print('更新订单状态响应状态码: ${response.statusCode}');
      print('更新订单状态响应内容: ${response.body}');

      return response.statusCode == 200;
    } catch (e) {
      print('更新订单状态失败: $e');
      return false;
    }
  }
}
